//
//  CheckVersion.m
//  华康通测试版
//
//  Created by leiyu on 16/12/13.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "CheckVersion.h"


#define ROW (283/358.5)

@implementation CheckVersion

- (UIView*)backView
{
    if (!_backView)
    {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT)];
        _backView.backgroundColor = YYColor;
        _backView.alpha = 0.65;
    }
    return _backView;
}

- (UILabel*)myLabel
{
    if (!_myLabel)
    {
        _myLabel = [[UILabel alloc]initWithFrame:CGRectMake((UISCREENWEITH - 180)/2, UISCREENHEIGHT - 80, 180, 30)];
        _myLabel.textAlignment = NSTextAlignmentCenter;
        _myLabel.font = [UIFont systemFontOfSize:15];
        _myLabel.textColor = FFFFFFColor;
        _myLabel.backgroundColor = YYColor;
        _myLabel.alpha = 0.7;
        _myLabel.layer.cornerRadius = 5.0;
        _myLabel.layer.masksToBounds = YES;
    }
    return _myLabel;
}
#pragma mark - 检查更新版本

/*
 {"platformType": "1",
 "orderType": "01",
 "requestService": "getUpdateVersion",
 "requestObject":
 {"equipmentFlag": "2"}}}
 
 {
 "responseObject": {
 "update_id": "2",
 "update_title": "第二版",
 "update_log": "1.修改二",
 "update_date": "2016-12-09",
 "update_version": "2",
 "mandatory_update": 0,
 "update_equipment": "2"
 },
 "resultCode": "0",
 "errorMessage": ""
 }
 update_id 唯一标识
 update_title:更新的标题
 update_log:更新的日志
 update_date:更新的日期
 update_version:更新的版本号
 mandatory_update:是否强制更新 (0代表强制更新，1代表不强制更新)
 update_equipment:对应设备标识符 (1代表安卓，2代表ios)
 */

- (void)checkBuild
{
    //如果是设置页面进入
    if (self.isSetSelf)
    {
        [self postData];
    }
    //如果是首页进入
    else
    {
        //从缓存取数据
        NSDictionary* oldTimeStr = [CacheData getCache:@"checkBuildTime_type"];
        NSLog(@"当前时间差= %@",[self getCurrentSeconds]);
        if (oldTimeStr)
        {
            //从缓存读取数据、判断是否强制更新
            if ([oldTimeStr[@"type"] integerValue] == 0)
            {
                //强制更新版本
                [self postData];
            }
            else
            {
                //非强制更新
                if ([[self getCurrentSeconds] integerValue] - [oldTimeStr[@"time"] integerValue] > 86400)
                {
                    [self postData];
                }
            }
        }
        else
        {
            //还没有缓存时间
            [self postData];
        }
    }
}

- (void)postData
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getUpdateVersion",
                           @"requestObject":@{
                                   @"equipmentFlag":@"2"
                                   }
                           };
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getUpdateVersionWithParam:json WithUrl:url];
}

//获取当前的日期时间离1970的时间
- (NSString*)getCurrentSeconds
{
    NSDate* date = [[NSDate alloc]init];
    NSDateFormatter* formater = [[NSDateFormatter alloc]init];
    formater.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString* time = [formater stringFromDate:date];
    //标准时间格式时间
    NSDate* now = [formater dateFromString:time];
    NSTimeInterval late = [now timeIntervalSince1970];
    NSString* lateStr = [NSString stringWithFormat:@"%.0f",late];
    return lateStr;
}

- (void)getUpdateVersionWithParam:(NSDictionary*)param WithUrl:(NSString*)url
{
    
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"检查更新版本json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    if (json[@"responseObject"])
                    {
                        if ([json[@"responseObject"][@"update_equipment"] isEqualToString:@"2"])
                        {
                            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                                //获取当前版本version
                                NSString* currentVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
                                NSLog(@"当前版本号:%@",currentVersion);
                                //缓存每次请求检查版本的时间，以便于下一次检查版本的时候，计算时间差
                                NSDictionary* dic = @{@"time":[self getCurrentSeconds],@"type":json[@"responseObject"][@"mandatory_update"]};
                                [CacheData saveCache:@"checkBuildTime_type" andCache:dic];
                                if (![json[@"responseObject"][@"update_version"] isEqualToString:currentVersion])
                                {
                                    //如果系统版本号 与当前版本号不一样，就需要更新版本
                                    if ([json[@"responseObject"][@"mandatory_update"] integerValue] == 0)
                                    {
                                        //强制更新
                                        NSLog(@"需要强制更新＋＋＋＋＋＋＋＋＋＋＋＋＋");
                                        //主线程更新ui 283:358.5
                                        [self createCheckViewWithLog:json[@"responseObject"][@"update_log"] withBool:NO];
                                    }
                                    else
                                    {
                                        //用户可以选择更新
                                        NSLog(@"用户选择更新＋＋＋＋＋＋＋＋＋＋＋＋＋");
                                        [self createCheckViewWithLog:json[@"responseObject"][@"update_log"] withBool:YES];
                                    }
                                }
                                else
                                {
                                    if (self.isSetSelf)
                                    {
                                        
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            //无需更新
                                            [[UIApplication sharedApplication].keyWindow addSubview:self.myLabel];
                                            self.myLabel.text = @"已经是最新版本!";
                                        });
                                        //动画删除label
                                        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
                                        dispatch_after(delay, dispatch_get_main_queue(), ^{
                                            [self.myLabel removeFromSuperview];
                                            self.myLabel = nil;
                                        });
                                    }
                                }
                            });
                        }
                    }
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"检查版本更新失败error = %@",error.userInfo);
        }];
    } failure:^{
        NSLog(@"检测到设备无网络连接！！！");
    }];
    
}
//------------------------------------------------------

//主线程创建弹出视图
- (void)createCheckViewWithLog:(NSString*)log withBool:(BOOL)isCancel
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.checkView = [CheckNewVersionView view];
        [self.checkView returnButtonWithBlock:^(NSInteger buttonTag) {
            if (buttonTag == 0)
            {
                [self cancelDeleteView];
            }
            else
            {
                [self goAppStore];
                if (isCancel)
                {
                    //延迟0.5秒关闭弹出视图
                    [self closeAlertView];
                }
            }
        }];
        self.checkView.frame = CGRectMake(45, (UISCREENHEIGHT - ((UISCREENWEITH - 90)/ROW))/2, UISCREENWEITH - 90, (UISCREENWEITH - 90)/ROW);
        self.checkView.textView.text = log;
        if (!isCancel)
        {
            [self.checkView.leftButton setHidden:YES];
            [self.checkView.centerView setHidden:YES];
            self.checkView.rightButton.frame = CGRectMake((UISCREENWEITH - 90)/4, self.checkView.frame.size.height - 50, (UISCREENWEITH - 90)/2, 50);
        }
        else
        {
            [self.checkView.leftButton setHidden:NO];
            [self.checkView.centerView setHidden:NO];
            self.checkView.leftButton.frame = CGRectMake(0, self.checkView.frame.size.height - 50, (UISCREENWEITH - 90)/2, 50);
            self.checkView.rightButton.frame = CGRectMake((UISCREENWEITH - 90)/2, self.checkView.frame.size.height - 50, (UISCREENWEITH - 90)/2, 50);
            self.checkView.centerView.frame = CGRectMake((UISCREENWEITH - 90)/2, self.checkView.frame.size.height - 50, 1, 50);
        }
        [[UIApplication sharedApplication].keyWindow addSubview:self.backView];
        [[UIApplication sharedApplication].keyWindow addSubview:self.checkView];
    });
}

//取消更新
- (void)cancelDeleteView
{
    [self.checkView removeFromSuperview];
    [self.backView removeFromSuperview];
    self.checkView = nil;
    self.backView = nil;
}

//去appstore更新版本  https://itunes.apple.com/us/app/hua-kang-tong/id1061175700
- (void)goAppStore
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/hua-kang-tong/id1061175700"]])
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/hua-kang-tong/id1061175700"]];
    }
}

//延迟0.5秒关闭弹出视图
- (void)closeAlertView
{
    //延迟0.5秒关闭弹出视图
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        [self cancelDeleteView];
    });
}


@end
